package cn.rongdao.jrkabao.ui.login;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import com.igexin.sdk.PushManager;
import com.mifengkong.frtools.app.FRApplication;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;
import com.mifengkong.greendao.bean.UserInfo;
import com.mifengkong.statistic.growingio.GIOUtils;
import com.mifengkong.statistic.talkingdata.TalkingData;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.bean.login.UserBean;
import cn.rongdao.jrkabao.dao.UserDao;
import cn.rongdao.jrkabao.model.login.SetPasswordModel;
import cn.rongdao.jrkabao.ui.login.uicomponent.LoginBottomUIComponent;
import cn.rongdao.jrkabao.ui.login.uicomponent.LoginInputUIComponent;
import cn.rongdao.jrkabao.ui.main.MainActivity;
import cn.rongdao.jrkabao.util.BigDecimalUtil;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.GetDefaultDataUtil;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function3;

/**
 * Created by jack on 2018/4/20
 */

public class ForgetPasswordActivity extends BaseAutoFinishActivity {

    public static final String PHONE = "phone";
    public static final String VERIFY_CODE = "verify_code";
    public static final String INVITE_CODE = "invite_code";
    public static final String IS_REGISTER = "is_register";

    public static void start(Context context, boolean isRegister, boolean isForgetPwd, String phone, String verifyCode, String inviteCode) {
        Bundle bundle = new Bundle();
        bundle.putString(PHONE, phone);
        bundle.putString(VERIFY_CODE, verifyCode);
        bundle.putString(INVITE_CODE, inviteCode);
        bundle.putBoolean(RegisterActivity.IS_FORGET_PWD, isForgetPwd);
        bundle.putBoolean(IS_REGISTER, isRegister);
        FRStartActivity.start(context, ForgetPasswordActivity.class, bundle);
    }

    public static void start(Context context, String phone, String verifyCode) {
        start(context, false, false, phone, verifyCode, "");
    }

    public static void startFromRegister(Context context, String phone, String verifyCode, String inviteCode) {
        start(context, true, false, phone, verifyCode, inviteCode);
    }

    public static void startFromForgetPwd(Context context, String phone, String verifyCode) {
        start(context, false, true, phone, verifyCode, "");
    }

    @BindView(R.id.afp_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.afp_password_input)
    LoginInputUIComponent passwordInput;
    @BindView(R.id.afp_confirm_password_input)
    LoginInputUIComponent confirmPwdInput;
    @BindView(R.id.afp_login_bottom)
    LoginBottomUIComponent loginBottomUIComponent;


    private CompositeDisposable compositeDisposable;
    private String phone;
    private String verifyCode;
    private String inviteCode;
    private boolean isRegister;
    private boolean isForgetPwd;

    @Override
    protected int layoutRes() {
        return R.layout.activity_forget_password;
    }

    @Override
    protected void initView() {
        super.initView();
        setAutoHideSoftInput(true);
        compositeDisposable = new CompositeDisposable();
        getIntentData();
        initUniqueId();
        initTitleBar();
        initInput();
        initListener();
    }

    private void initListener() {
        loginBottomUIComponent.setOnLoginClickListener(isRegister ? "注册" : isForgetPwd ? "去登录" : "完成", new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                setPassword();
            }
        });
    }

    private void setPassword() {
        if (CommonUtil.isPasswordCorrect(passwordInput.getInputContent(), confirmPwdInput.getInputContent())
                && CommonUtil.checkPassword(passwordInput.getInputContent(), confirmPwdInput.getInputContent())){
            SetPasswordModel.getInstance()
                    .addParams("phone", phone)
                    .addParams("password", BigDecimalUtil.getMD5(passwordInput.getInputContent()))
                    .addParams("confirm_password", BigDecimalUtil.getMD5(confirmPwdInput.getInputContent()))
                    .addParams("type", isRegister ? "1" : "2")
                    .addParams("invitation_code", inviteCode)
                    .addParams("validate_code", verifyCode)
                    .addParams(!isForgetPwd ? GetDefaultDataUtil.getDefaultUserInfo(thisActivity()) : null)
                    .execute(new FRBaseObserver<UserBean>(this, "加载中，请稍候...") {
                        @Override
                        protected void onBaseNext(UserBean data) {
                            if (isForgetPwd) {
                                LoginActivity.start(thisActivity());
                            } else {
                                PushManager.getInstance().turnOnPush(thisActivity());
                                UserDao.getInstance().insertObject(new UserInfo(data.getUser_id(), phone, data.getToken()));
                                GIOUtils.setCS1(FRApplication.getInstance().getPackageName(), data.getUser_id());
                                TalkingData.onLogin(data.getUser_id());
                                TalkingData.onRegister(data.getUser_id());
                                MainActivity.Companion.start(thisActivity());
                            }
                            finish();
                        }
                    });
        }
    }

    private void getIntentData() {
        phone = getIntent().getStringExtra(PHONE);
        verifyCode = getIntent().getStringExtra(VERIFY_CODE);
        inviteCode = getIntent().getStringExtra(INVITE_CODE);
        isRegister = getIntent().getBooleanExtra(IS_REGISTER, false);
        isForgetPwd = getIntent().getBooleanExtra(RegisterActivity.IS_FORGET_PWD, false);
        if (isForgetPwd) {
            loginBottomUIComponent.setProtocolGone();
        }
    }

    private void initInput() {
        passwordInput.setInputMaxLength(20);
        passwordInput.setHint(isForgetPwd ? "请输入新密码(6-20位字母或数字组合)" : "请输入密码(6-20位字母或数字组合)");
        passwordInput.initDelete();
        passwordInput.setPassword();

        confirmPwdInput.setInputMaxLength(20);
        confirmPwdInput.setHint(isForgetPwd ? "请确认新密码(6-20位字母或数字组合)" : "请确认密码(6-20位字母或数字组合)");
        confirmPwdInput.initDelete();
        confirmPwdInput.setPassword();

        compositeDisposable.add(Observable.combineLatest(passwordInput.getInputObservable(), confirmPwdInput.getInputObservable(), loginBottomUIComponent.getCheckBoxObservable(), new Function3<CharSequence, CharSequence, Boolean, Boolean>() {
            @Override
            public Boolean apply(CharSequence passwordSequence, CharSequence confirmPwdSequence, Boolean aBoolean) throws Exception {
                if (isForgetPwd) {
                    return !FRString.isEmpty(FRString.valueOf(passwordSequence), FRString.valueOf(confirmPwdSequence));
                } else {
                    return !FRString.isEmpty(FRString.valueOf(passwordSequence), FRString.valueOf(confirmPwdSequence)) && aBoolean;
                }
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                loginBottomUIComponent.setLoginBtnEnable(aBoolean);
            }
        }));
    }

    private void initTitleBar() {
        titleBarUIComponent.initTitleBlack(isForgetPwd ? "忘记密码" : isRegister ? "注册" : "设置密码");
        titleBarUIComponent.initLeftBackBlack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected boolean useBlackStatusBarOnWhite() {
        return true;
    }

    @Override
    public void onDestroy() {
        passwordInput.onDestroy();
        confirmPwdInput.onDestroy();
        loginBottomUIComponent.onDestroy();
        if (null != compositeDisposable) {
            compositeDisposable.dispose();
            compositeDisposable = null;
        }
        super.onDestroy();
    }
}